from django_redis import get_redis_connection
from rest_framework import serializers
from drf_haystack.serializers import HaystackSerializer

from goods.search_indexes import SKUIndex
from .models import SKU


class CategoriesSerializer(serializers.ModelSerializer):

    class Meta:

        model = SKU
        fields = '__all__'


class SKUIndexSerializer(HaystackSerializer):
    """
      SKU索引结果数据序列化器
      """
    object = CategoriesSerializer(read_only=True)   # SKU商品数据对象序列化返回

    class Meta:
        index_classes = [SKUIndex]
        fields = ('text', 'object')


class SKUHistorySerializer(serializers.Serializer):

    sku_id = serializers.IntegerField(min_value=1)
    # 判断sku_id是否存在
    def validate(self, attrs):

        try:
            SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')

        return attrs

    def create(self, validated_data):

        user = self.context['request'].user
        # 建立redis连接
        conn = get_redis_connection('history')
        # 判断sku_id是否保存过     lrem删除
        conn.lrem('history_%s' %user.id, 0, validated_data['sku_id'])
        # 写入sku_id
        conn.lpush('history_%s' %user.id, validated_data['sku_id'])
        # 控制保存数量
        conn.ltrim('history_%s' %user.id, 0, 4)
        # 返回结果
        return validated_data